// pages/search_main/search_main.js
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        course: [],
        cate_id: '',
        keyword: '',
        cate: [],
        page: 1,
        is_empty: false,
        
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getCate();
        this.renderCourseList();
    },

    /**
     * 下拉刷新
     */
    onPullDownRefresh: function () {
        wx.showLoading({
            title: '正在刷新',
        })
        this.renderCourseList(function () {
            setTimeout(function () {
                wx.stopPullDownRefresh();
                wx.hideLoading()
            }, 500)
        })
    },

    /**
     * 上拉分页加载
     */
    onReachBottom: function () {
        this.getCourseList();
    },

    //搜索
    search: function (input) {
        let keyword = input.detail.value,
            setdata = {};
        setdata['keyword'] = keyword;
        setdata['page'] = 1;
        setdata['course'] = [];
        this.setData(setdata);
        this.getCourseList();

    },

    //分类
    change_tab: function (e) {
        let setdata = {};
        setdata['cate_id'] = e.currentTarget.dataset.cate_id
        setdata['page'] = 1;
        setdata['course'] = [];
        this.setData(setdata);
        this.getCourseList();
    },

    //重新渲染商品数据
    renderCourseList: function (cb) {
        let setdata = {};
        setdata['course'] = [];
        setdata['page'] = 1;
        this.setData(setdata)
        this.getCourseList(cb);
    },

    //获取课程列表
    getCourseList: function (cb) {
        let _this = this,
        cate_id = _this.data.cate_id,
        keyword = _this.data.keyword,
        page = _this.data.page,
        origin = _this.data.course;
        app._get('/api/login/student/getCourseInterest', {
            page: page,
            cate_id: cate_id,
            keyword: keyword
        }, function (response) {
            let data = response.data.data;
            data = origin.length > 0 ? origin.concat(data) : data;
            let setdata = {};
            if (data.length == 0) {
                setdata['is_empty'] = true;
            } else {
                setdata['is_empty'] = false;
                setdata['course'] = data;
                setdata['page'] = page + 1;
            }
            _this.setData(setdata);
        })
        typeof cb == 'function' && cb();
    },

    //获取分类
    getCate: function (cb) {
        let _this = this;
        app._get('/api/login/course/getAllCate', null, function (response) {
            _this.setData({
                cate: response.data.data
            })
        })
    },

    /**
     * 去课程详情
     */
    toDetail: function(e){
        wx.navigateTo({
          url: '/pages/course_detail/course_detail?course_id='+e.currentTarget.dataset.course_id,
        })
    },

})